package com.rh.bmw4s.view.fragdialog;

import android.app.DialogFragment;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.rh.bmw4s.R;
import com.rh.bmw4s.adapter.FianlAdapter;
import com.rh.bmw4s.bean.ThirdSearchBean;
import com.rh.bmw4s.comm.ConfigValue;
import com.rh.bmw4s.comm.Constant;
import com.rh.bmw4s.utills.LogUtils;
import com.rh.bmw4s.utills.SPUtils;
import com.rh.bmw4s.utills.ScreenUtils;
import com.rh.bmw4s.utills.SizeUtils;
import com.rh.bmw4s.utills.ToastUtils;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.List;


/**
 * 车辆三级搜索，第三级
 */

public class ParamListDialog extends DialogFragment implements View.OnClickListener {

    private int anInt;
    private int carId;
    private Gson gson = null;
    private TextView textView2;
    private TextView dangwei1, dangwei2;
    private TagFlowLayout flowPaiLiang;
    private RelativeLayout relBianSuXiang; //变速箱 （手动挡 自动挡）

    private LRecyclerView finalRecy;
    private FianlAdapter fianlAdapter;
    private LRecyclerViewAdapter lrecyclerViewAdapter3;

    @Override
    public void onStart() {
        super.onStart();
        //获取屏幕信息
        DisplayMetrics metrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);

        Window window = getDialog().getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = ScreenUtils.getScreenWidth() / 2;
        params.height = ScreenUtils.getScreenHeight() - SizeUtils.dp2px(50) - SizeUtils.getStatusBarHeight();
        params.gravity = Gravity.RIGHT | Gravity.BOTTOM;
        window.setAttributes(params);
//        window.setGravity(Gravity.CENTER);
//        //这里用屏幕高度，不覆盖状态栏
        //window.setLayout((int) (metrics.widthPixels / 2), ScreenUtils.getScreenHeight());
        //设置布局部分的背景色
        window.setBackgroundDrawable(new ColorDrawable(000000));
        //整体背景色(设置透明度)
        window.setDimAmount(0.5f);
        //动画
        //window.setWindowAnimations(R.style.BottmoDialogAnim);
        getDialog().setCanceledOnTouchOutside(true);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);

        View view = inflater.inflate(R.layout.custom_bottom, container);
        gson = new Gson();
        anInt = SPUtils.getInstance().getInt(ConfigValue.userId);
        //动态获取item宽度
        int width = ScreenUtils.getScreenWidth() / 2;
        itemWidth = (int) (width - SizeUtils.dp2px(40f)) / 3;
        Bundle bundle = getArguments();
        if (bundle != null) {
            carId = bundle.getInt("carid");
        }

        relBianSuXiang = view.findViewById(R.id.rel_biansuxiang);
        textView2 = view.findViewById(R.id.tv_back2);
        finalRecy = view.findViewById(R.id.recy_final);
        dangwei1 = view.findViewById(R.id.third_dangwei_1);
        dangwei2 = view.findViewById(R.id.third_dangwei_2);
        flowPaiLiang = view.findViewById(R.id.final_pailiang_flow);
        flowPaiLiang.setMaxSelectCount(1);
        initDetailView();

        textView2.setOnClickListener(this);
        dangwei1.setOnClickListener(this);
        dangwei2.setOnClickListener(this);

        return view;
    }


    private void initDetailView() {
        finalRecy.setLayoutManager(new LinearLayoutManager(getDialog().getContext()));
        fianlAdapter = new FianlAdapter(getDialog().getContext());
        lrecyclerViewAdapter3 = new LRecyclerViewAdapter(fianlAdapter);
        finalRecy.setAdapter(lrecyclerViewAdapter3);
        DividerDecoration divider = new DividerDecoration.Builder(getDialog().getContext())
                .setHeight(R.dimen.divider_height_1)
                .setPadding(R.dimen.divider_padding)
                .setColorResource(R.color.line_1)
                .build();
        finalRecy.addItemDecoration(divider);
        finalRecy.setLoadMoreEnabled(false);
        finalRecy.setPullRefreshEnabled(false);
        getdatas();


        fianlAdapter.setOpenFinalItemClick(new FianlAdapter.OpenFinalItemClick() {
            @Override
            public void itemFinalItemClick(ThirdSearchBean.DatasBean.YearsBean.ListBean bean) {

//                Intent intent2 = new Intent(getDialog().getContext(), ShowCarTypeActivity.class);
//                intent2.putExtra("url", "http://4s.liexianghudong.com/index.php/home/index/back/mem_id/" + anInt + "/goods_id/" + bean.getId());
//                getDialog().getContext().startActivity(intent2);

                // EventBus.getDefault().postSticky(new EventInfo(11));
                Intent intent = new Intent();
                intent.putExtra("selectCarId", bean.getId());
                intent.putExtra("selectCarName", bean.getGoods_name());
                getActivity().setResult(135, intent);
                getActivity().finish();
            }
        });
    }


    private int tempDangWei1 = 0;
    private int tempDangWei2 = 0;

    private void getdatas() {

        OkGo.<String>post(Constant.ThirdSearch)
                .params("car_brand", carId)
                .execute(new StringCallback() {

                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.d("333", response.body().toString());
                        ThirdSearchBean searchBean = gson.fromJson(response.body().toString(), ThirdSearchBean.class);

                        List<ThirdSearchBean.DatasBean.List1Bean> list1 = searchBean.getDatas().getList1();

                        if (list1 != null && list1.size() > 0) {
                            relBianSuXiang.setVisibility(View.VISIBLE);
                            //手自动挡
                            dangwei1.setText(list1.get(0).getName());
                            tempDangWei1 = list1.get(0).getId();
                            //默认选择第一个档位
                            //tempCurrentDangWei = tempDangWei1;
                            if (list1.size() == 1) {
                                dangwei2.setVisibility(View.GONE);
                            } else {
                                dangwei2.setVisibility(View.VISIBLE);
                                dangwei2.setText(list1.get(1).getName());
                                tempDangWei2 = list1.get(1).getId();
                            }
                        } else {
                            relBianSuXiang.setVisibility(View.GONE);
                        }

                        //排量
                        ThirdSearchBean.DatasBean datas = searchBean.getDatas();
                        if (datas != null) {
                            getPaiLiang(datas);
                        }

                        List<ThirdSearchBean.DatasBean.YearsBean> yearsList = searchBean.getDatas().getYears();
                        if (yearsList == null || yearsList.size() == 0) {
                            ToastUtils.toastForShort(getActivity(), "没有符合的车辆");
                            return;
                        }
                        fianlAdapter.setDataList(yearsList);
                        finalRecy.refreshComplete(yearsList.size());
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LogUtils.d("333", "33333333333333");
                    }
                });
    }

    private int itemWidth = 0;
    private int lastPosi = 1000;

    /**
     * 获取排量信息
     */
    public void getPaiLiang(final ThirdSearchBean.DatasBean datas) {

        //List<ThirdSearchBean.DatasBean.List2Bean> beanList = datas.getList2();

        TagAdapter<ThirdSearchBean.DatasBean.List2Bean> tagAdapter = new TagAdapter<ThirdSearchBean.DatasBean.List2Bean>(datas.getList2()) {
            @Override
            public View getView(FlowLayout parent, int position, ThirdSearchBean.DatasBean.List2Bean bean) {
                String tip = bean.getPailiang();
                TextView textView = (TextView) LayoutInflater.from(getActivity())
                        .inflate(R.layout.item_final_pailiang, flowPaiLiang, false);
                textView.setText(tip);
                textView.getLayoutParams().width = itemWidth;
                if (TextUtils.isEmpty(tip)) {
                    textView.setVisibility(View.GONE);
                }
                return textView;
            }

            @Override
            public void unSelected(int position, View view) {
                super.unSelected(position, view);
            }

            @Override
            public void onSelected(int position, View view) {
                super.onSelected(position, view);
            }

            @Override
            public boolean setSelected(int position, ThirdSearchBean.DatasBean.List2Bean bean) {
                return super.setSelected(position, bean);
            }

        };
        //添加热门标签数据
        flowPaiLiang.setAdapter(tagAdapter);
        //热门标签点击事件
        flowPaiLiang.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                fianlAdapter.clear();
                lrecyclerViewAdapter3.notifyDataSetChanged();//必须调用此方法

                if (lastPosi == position) {
                    //取消选中
                    selectPaiLiang(0);
                    lastPosi = 1000;
                } else {
                    lastPosi = position;
                    String pailiang = datas.getList2().get(position).getPailiang();
                    selectPaiLiang(Integer.parseInt(pailiang));
                }


                return false;
            }
        });

    }

    private PostRequest<String> request1 = null;

    /**
     * 选择排量
     */
    private void selectPaiLiang(int size) {

        if (size == 0) {
            //取消选择排量
            request1 = OkGo.<String>post(Constant.ThirdSearch)
                    .params("car_brand", carId)
                    .params("gearbox", tempCurrentDangWei);
        } else {
            request1 = OkGo.<String>post(Constant.ThirdSearch)
                    .params("car_brand", carId)
                    .params("gearbox", tempCurrentDangWei)
                    .params("pailiang", size);
        }
        request1.execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                LogUtils.d("333", response.body().toString());
                ThirdSearchBean searchBean = gson.fromJson(response.body().toString(), ThirdSearchBean.class);

                List<ThirdSearchBean.DatasBean.YearsBean> yearsList = searchBean.getDatas().getYears();
                if (yearsList == null || yearsList.size() == 0) {
                    ToastUtils.toastForShort(getActivity(), "没有符合的车辆");
                    return;
                }
                fianlAdapter.setDataList(yearsList);
                finalRecy.refreshComplete(yearsList.size());
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                LogUtils.d("333", "33333333333333");
                ToastUtils.toastForShort(getActivity(), "请求信息失败");
            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_back2:
                slideDialogOnClick.closeDialog();
                break;
            case R.id.third_dangwei_1:
                //dangwei1.setBackground(R.drawable.tag_bg);
                flowPaiLiang.removeAllViews();
                fianlAdapter.clear();
                lrecyclerViewAdapter3.notifyDataSetChanged();//必须调用此方法

                changeBg(1);
                selectDangWei(1);
                break;
            case R.id.third_dangwei_2:
                flowPaiLiang.removeAllViews();
                fianlAdapter.clear();
                lrecyclerViewAdapter3.notifyDataSetChanged();//必须调用此方法

                changeBg(2);
                selectDangWei(2);
                break;
        }

    }

    /**
     * 修改背景色
     */
    private void changeBg(int i) {
        if (i == 1) {
            dangwei1.setTextColor(getResources().getColor(R.color.colorAccent));
            dangwei1.setBackground(getResources().getDrawable(R.drawable.checked_bg));
            dangwei2.setTextColor(getResources().getColor(R.color.first_textcolor));
            dangwei2.setBackground(getResources().getDrawable(R.drawable.normal_bg));
        } else {
            dangwei1.setTextColor(getResources().getColor(R.color.first_textcolor));
            dangwei1.setBackground(getResources().getDrawable(R.drawable.normal_bg));
            dangwei2.setTextColor(getResources().getColor(R.color.colorAccent));
            dangwei2.setBackground(getResources().getDrawable(R.drawable.checked_bg));
        }
    }

    private PostRequest<String> request = null;
    private int tempCurrentDangWei = 0;

    /**
     * 选择不同档位时,改变数据
     */
    private void selectDangWei(int position) {
        lastPosi = 1000;
        if (position == 1) {
            tempCurrentDangWei = tempDangWei1;
            request = OkGo.<String>post(Constant.ThirdSearch).params("car_brand", carId).params("gearbox", tempDangWei1);
        } else {
            tempCurrentDangWei = tempDangWei2;
            request = OkGo.<String>post(Constant.ThirdSearch).params("car_brand", carId).params("gearbox", tempDangWei2);
        }
        request.execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                LogUtils.d("333", response.body().toString());
                ThirdSearchBean searchBean = gson.fromJson(response.body().toString(), ThirdSearchBean.class);

                //排量
                ThirdSearchBean.DatasBean datas = searchBean.getDatas();
                if (datas != null) {
                    getPaiLiang(datas);
                }

                List<ThirdSearchBean.DatasBean.YearsBean> yearsList = searchBean.getDatas().getYears();
                if (yearsList == null || yearsList.size() == 0) {
                    ToastUtils.toastForShort(getActivity(), "没有符合的车辆");
                    return;
                }
                fianlAdapter.setDataList(yearsList);
                finalRecy.refreshComplete(yearsList.size());
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                LogUtils.d("333", "33333333333333");
                ToastUtils.toastForShort(getActivity(), "请求信息失败");
            }
        });

    }


    //定义接口
    public interface slideDialogOnClick {
        void closeDialog();
    }

    private slideDialogOnClick slideDialogOnClick;

    public void setSlideDialogOnClick(ParamListDialog.slideDialogOnClick slideDialogOnClick) {
        this.slideDialogOnClick = slideDialogOnClick;
    }
}
